"""
模型管理路由
"""

from fastapi import APIRouter, HTTPException, Query
from typing import List, Optional
import time

from ..models import (
    ModelsListResponse, ModelInfoResponse, ModelCreateRequest,
    BaseResponse, ErrorResponse, StatisticsResponse
)
from ..storage import data_manager, ModelInfo
from ..logger import logger
from ..utils import generate_id

router = APIRouter()


@router.get("/models", response_model=ModelsListResponse)
async def get_models(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(100, ge=1, le=1000, description="每页数量"),
    model_type: Optional[str] = Query(None, description="模型类型过滤"),
    status: Optional[str] = Query(None, description="状态过滤"),
    search: Optional[str] = Query(None, description="搜索关键词")
):
    """获取模型列表"""
    try:
        # 从存储获取所有模型
        models = await data_manager.get_models()
        
        # 应用过滤器
        filtered_models = models
        
        if model_type:
            filtered_models = [m for m in filtered_models if m.model_type == model_type]
            
        if status:
            filtered_models = [m for m in filtered_models if m.status == status]
            
        if search:
            search_lower = search.lower()
            filtered_models = [
                m for m in filtered_models 
                if search_lower in m.name.lower() 
                or search_lower in m.description.lower()
                or search_lower in m.author.lower()
            ]
        
        # 分页
        total = len(filtered_models)
        start_idx = (page - 1) * page_size
        end_idx = start_idx + page_size
        page_models = filtered_models[start_idx:end_idx]
        
        # 转换为响应模型
        model_responses = [
            ModelInfoResponse(
                id=model.id,
                name=model.name,
                version=model.version,
                model_type=model.model_type,
                description=model.description,
                author=model.author,
                size=model.size,
                upload_time=model.upload_time,
                last_update=model.last_update,
                status=model.status,
                download_url=model.download_url,
                checksum=model.checksum,
                server_id=model.server_id,
                tags=model.tags,
                requirements=model.requirements,
                metrics=model.metrics
            )
            for model in page_models
        ]
        
        return ModelsListResponse(
            models=model_responses,
            total=total,
            page=page,
            page_size=page_size,
            message=f"Found {total} models"
        )
        
    except Exception as e:
        logger.error(f"Failed to get models: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve models")


@router.get("/models/{model_id}", response_model=ModelInfoResponse)
async def get_model(model_id: str):
    """获取指定模型详情"""
    try:
        model = await data_manager.get_model_by_id(model_id)
        
        if not model:
            raise HTTPException(status_code=404, detail="Model not found")
        
        return ModelInfoResponse(
            id=model.id,
            name=model.name,
            version=model.version,
            model_type=model.model_type,
            description=model.description,
            author=model.author,
            size=model.size,
            upload_time=model.upload_time,
            last_update=model.last_update,
            status=model.status,
            download_url=model.download_url,
            checksum=model.checksum,
            server_id=model.server_id,
            tags=model.tags,
            requirements=model.requirements,
            metrics=model.metrics
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get model {model_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve model")


@router.post("/models", response_model=BaseResponse)
async def create_model(model_request: ModelCreateRequest):
    """创建新模型"""
    try:
        # 检查模型名称是否已存在
        existing_models = await data_manager.get_models()
        for existing_model in existing_models:
            if (existing_model.name == model_request.name and 
                existing_model.version == model_request.version):
                raise HTTPException(
                    status_code=409, 
                    detail=f"Model {model_request.name} v{model_request.version} already exists"
                )
        
        # 创建新模型
        current_time = time.time()
        new_model = ModelInfo(
            id=generate_id(),
            name=model_request.name,
            version=model_request.version,
            model_type=model_request.model_type,
            description=model_request.description,
            author=model_request.author,
            size=model_request.size,
            upload_time=current_time,
            last_update=current_time,
            status="available",
            download_url=model_request.download_url,
            checksum=model_request.checksum or "",
            server_id="local",
            tags=model_request.tags,
            requirements=model_request.requirements,
            metrics={}
        )
        
        # 保存到存储
        await data_manager.add_model(new_model)
        
        logger.info(f"Created new model: {new_model.name} v{new_model.version}")
        
        return BaseResponse(
            message=f"Model {new_model.name} v{new_model.version} created successfully"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to create model: {e}")
        raise HTTPException(status_code=500, detail="Failed to create model")


@router.put("/models/{model_id}/status", response_model=BaseResponse)
async def update_model_status(model_id: str, status_data: dict):
    """更新模型状态"""
    try:
        # 检查模型是否存在
        model = await data_manager.get_model_by_id(model_id)
        if not model:
            raise HTTPException(status_code=404, detail="Model not found")

        # 验证状态值
        new_status = status_data.get("status")
        valid_statuses = ["available", "unavailable", "loading", "error", "maintenance"]
        if new_status not in valid_statuses:
            raise HTTPException(
                status_code=400,
                detail=f"Invalid status. Must be one of: {', '.join(valid_statuses)}"
            )

        # 更新模型状态
        model.status = new_status
        model.last_update = time.time()
        await data_manager.update_model(model)

        logger.info(f"Updated model status: {model.name} -> {new_status}")

        return BaseResponse(
            message=f"Model {model.name} status updated to {new_status}"
        )

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to update model {model_id} status: {e}")
        raise HTTPException(status_code=500, detail="Failed to update model status")


@router.delete("/models/{model_id}", response_model=BaseResponse)
async def delete_model(model_id: str):
    """删除模型"""
    try:
        # 检查模型是否存在
        model = await data_manager.get_model_by_id(model_id)
        if not model:
            raise HTTPException(status_code=404, detail="Model not found")

        # 删除模型
        await data_manager.delete_model(model_id)

        logger.info(f"Deleted model: {model.name} v{model.version}")

        return BaseResponse(
            message=f"Model {model.name} v{model.version} deleted successfully"
        )

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to delete model {model_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to delete model")


@router.get("/models/statistics", response_model=StatisticsResponse)
async def get_models_statistics():
    """获取模型统计信息"""
    try:
        models = await data_manager.get_models()
        
        # 统计各种信息
        total_models = len(models)
        
        models_by_type = {}
        models_by_status = {}
        
        for model in models:
            # 按类型统计
            model_type = model.model_type
            models_by_type[model_type] = models_by_type.get(model_type, 0) + 1
            
            # 按状态统计
            status = model.status
            models_by_status[status] = models_by_status.get(status, 0) + 1
        
        # 最近活动（最近上传的模型）
        recent_models = sorted(models, key=lambda x: x.upload_time, reverse=True)[:10]
        recent_activities = [
            {
                "type": "model_uploaded",
                "model_name": model.name,
                "model_version": model.version,
                "timestamp": model.upload_time,
                "author": model.author
            }
            for model in recent_models
        ]
        
        return StatisticsResponse(
            total_models=total_models,
            models_by_type=models_by_type,
            models_by_status=models_by_status,
            recent_activities=recent_activities
        )
        
    except Exception as e:
        logger.error(f"Failed to get statistics: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve statistics")
